package games.gong.durid.controller;

/**
 * @ClassName AuthController
 * @PackageName games.gong.durid.controller
 * @projectName springboot
 * @Description TODO
 * @Author games
 * @Date 2025/8/19 下午4:30
 * @Version 1.0
 */

import games.gong.durid.dto.LoginDTO;
import games.gong.durid.dto.RegisterDTO;
import games.gong.durid.vo.LoginVO;
import games.gong.durid.entity.User;
import games.gong.durid.security.JwtUtil;
import games.gong.durid.service.impl.UserServiceImpl;
import games.gong.durid.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    private final UserServiceImpl userServiceImpl;
    private final JwtUtil jwtUtil;
    private final PasswordEncoder passwordEncoder;

    public AuthController(UserServiceImpl userServiceImpl, JwtUtil jwtUtil, PasswordEncoder passwordEncoder) {
        this.userServiceImpl = userServiceImpl;
        this.jwtUtil = jwtUtil;
        this.passwordEncoder = passwordEncoder;
    }

    @PostMapping("/login")
    public R<LoginVO> login(@RequestBody LoginDTO request) {
        logger.info("用户登录请求: {}", request);
        User user = userServiceImpl.getUserByUsername(request.getUsername());
        logger.info("根据用户名查找用户结果: {}", user);

        if (user == null) {
            logger.warn("用户 {} 不存在", request.getUsername());
            return R.error(401, "用户名或密码错误");
        }

        logger.info("数据库中的密码: {}", user.getPassword());
        logger.info("用户输入的密码: {}", request.getPassword());
        
        // 修复密码验证逻辑：直接比较用户输入的明文密码和数据库中的加密密码
        boolean passwordMatches = passwordEncoder.matches(request.getPassword(), user.getPassword());
        logger.info("密码匹配结果: {}", passwordMatches);

        if (!passwordMatches) {
            return R.error(401, "用户名或密码错误");
        }

        String token = jwtUtil.generateToken(user.getId(), user.getUsername());

        LoginVO resp = new LoginVO();
        resp.setToken(token);
        resp.setUsername(user.getUsername());
        resp.setUserId(user.getId());

        logger.info("用户 {} 登录成功，生成token: {}", user.getUsername(), token);
        return R.success("login.success", resp);
    }

    @PostMapping("/register")
    public R<String> register(@RequestBody RegisterDTO registerDTO) {
        logger.info("用户注册请求: {}", registerDTO);
        
        // 将RegisterDTO转换为User实体
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());
        user.setEmail(registerDTO.getEmail());
        
        // 密码加密在UserService中处理
        userServiceImpl.addUser(user);
        logger.info("用户 {} 注册成功", user.getUsername());
        return R.success("注册成功", null);
    }
}